package com.houkunlin.wake.lan.utils;

import com.houkunlin.system.common.exception.BusinessException;
import com.houkunlin.wake.lan.cmd.Computer;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

/**
 * 唤醒主机工具
 *
 * @author HouKunLin
 */
@Slf4j
public class WakeOnLan {
    private WakeOnLan() {
    }

    /**
     * 构建数据包内容
     *
     * @param macBytes MAC 地址
     * @return 数据包
     */
    public static DatagramPacket getDatagramPacket(byte[] macBytes) {
        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
        for (int i = 0; i < 6; i++) {
            stream.write(0xFF);
        }
        for (int i = 0; i < 16; i++) {
            stream.writeBytes(macBytes);
        }
        final byte[] bytes = stream.toByteArray();
        return new DatagramPacket(bytes, bytes.length);
    }

    /**
     * 发送数据包唤醒主机
     *
     * @param computer 电脑信息
     */
    public static void bootstrap(Computer computer) {
        log.debug("启动主机：{}", computer);
        try (final MulticastSocket socket = new MulticastSocket(computer.getPort())) {
            socket.setSoTimeout(1);
            socket.connect(computer.getGatewayAddress(), computer.getPort());
            socket.send(getDatagramPacket(computer.getMacBytes()));
            socket.disconnect();
        } catch (IOException e) {
            throw new BusinessException("唤醒电脑失败", e);
        }
    }

}
